package ru.compscicenter.uno.wizard;

import ru.compscicenter.uno.GameSettings;
import ru.compscicenter.uno.log.Logger;
import ru.compscicenter.uno.net.UDPClient;
import ru.compscicenter.uno.util.ImagePool;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.TreeSet;

/**
 * User: SLeeP
 * Date: 03.03.12
 * Time: 5:11
 */
public class Panel2Client extends JPanel {
    public final static String MANUAL = "manual";
    public final static String SEARCH = "search";
    private String address;

    private javax.swing.JLabel anotherBlankSpace;
    private javax.swing.JLabel blankSpace;
    private static javax.swing.ButtonGroup roleGroup;
    private javax.swing.JRadioButton manualRadioButton;
    private javax.swing.JRadioButton searchRadioButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel welcomeTitle;
    private javax.swing.JLabel yetAnotherBlankSpace1;
    private JFormattedTextField serverAddress;
    private static DefaultListModel<Object> listModel;
    private JList<Object> serversJList;
    private JScrollPane scrollPane;
    private JButton refreshButton;
    private static UDPClient udpClient;

    private static TreeSet<String> availableServers;

    private static JPanel contentPanel;
    private JLabel iconLabel;
    private JSeparator separator;
    private JLabel textLabel;
    private JPanel titlePanel;
    private GameSettings gameSettings;
    private ImageIcon icon;

    public Panel2Client(GameSettings gameSettings) throws IOException {

        super();
        this.gameSettings = gameSettings;
        availableServers = new TreeSet<String>();
        udpClient = new UDPClient();
        this.gameSettings = gameSettings;

        iconLabel = new JLabel();
        contentPanel = getContentPanel();
        contentPanel.setBorder(new EmptyBorder(new Insets(10, 10, 10, 10)));

        icon = new ImageIcon(ImagePool.getImage(Wizard.unoIconDIR, 250, 383));

        setLayout(new java.awt.BorderLayout());

        if (icon != null)
            iconLabel.setIcon(icon);

        iconLabel.setBorder(new EtchedBorder(EtchedBorder.RAISED));

        add(iconLabel, BorderLayout.WEST);

        JPanel secondaryPanel = new JPanel();
        secondaryPanel.add(contentPanel, BorderLayout.NORTH);
        add(secondaryPanel, BorderLayout.CENTER);
    }

    private JPanel getContentPanel() {

        JPanel contentPanel1 = new JPanel();

        roleGroup = new javax.swing.ButtonGroup();
        welcomeTitle = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jPanel1.setLayout(new BoxLayout(jPanel1, BoxLayout.Y_AXIS));
        blankSpace = new javax.swing.JLabel();
        refreshButton = new JButton("Refresh");
        serverAddress = new JFormattedTextField();
        listModel = new DefaultListModel<Object>();

        serversJList = new JList<Object>(listModel);
        scrollPane = new JScrollPane(serversJList);
        //scrollPane.setPreferredSize(new Dimension(200, 120));
        addRefreshButtonListener();
        addSelectListener();

        serversJList.setLayoutOrientation(JList.VERTICAL);
        serversJList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        anotherBlankSpace = new javax.swing.JLabel();
        yetAnotherBlankSpace1 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        jLabel1.setText("You can choose server from list: ");
        jPanel1.add(jLabel1);
        jPanel1.add(scrollPane);
        jPanel1.add(yetAnotherBlankSpace1);
        jPanel1.add(refreshButton);
        jPanel1.add(anotherBlankSpace);
        jLabel2.setText("or write IP of the server here: ");
        jPanel1.add(jLabel2);
        jPanel1.add(serverAddress);


        contentPanel1.add(jPanel1, java.awt.BorderLayout.CENTER);

        return contentPanel1;
    }

    private void serverSearch() {
        Thread serverSearch = new Thread(
            new Runnable() {
                public void run() {
                    updateAvailableServers();
                }
            }
        );
        serverSearch.start();
    }

    public void addRefreshButtonListener() {
        refreshButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Refresh button pressed");
                serverSearch();
            }
        });
    }

    private void addSelectListener() {
        serversJList.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting() == false) {
                    if (serversJList.getSelectedIndex() != -1) {
                        String addr = serversJList.getSelectedValue().toString().trim();
                        serverAddress.setText(addr);
                        gameSettings.address = serverAddress.getText();
                    }
                }
            }
        });
    }


    public void addIpChangeListener(DocumentListener dl) {
        serverAddress.getDocument().addDocumentListener(dl);
    }

    public void updateAvailableServers() {
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    availableServers = udpClient.findServers();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                setCursor(Cursor.getDefaultCursor());
                listModel.clear();
                for (int i = 0; i != availableServers.size(); i++) {
                    System.out.println(availableServers.toArray()[i]);
                    listModel.addElement(availableServers.toArray()[i]);
                }
            }
        }).start();
    }

    public static void showMessage(String msg) {
        JOptionPane.showMessageDialog(contentPanel, msg);
    }

    public String getAddress() {
        return serverAddress.getText();
    }

    public void setListNoChosen() {
        serversJList.clearSelection();
    }

    public boolean checkIP(String ipAddress) {
        try {
            if (ipAddress.matches("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\:[0-9]{1,6}")) {
                String[] parts = ipAddress.split("\\:");
                String[] ip = parts[0].split("\\.");
                String port = parts[1];

                for (String s : ip) {
                    int i = Integer.parseInt(s);
                    if (i < 0 || i > 255) {
                        return false;
                    }
                }
                return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }
}
